home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2004 #2 / K-CD-2-2004.ISO / OpenOffice Sv / f_0397 / python-core-2.2.2 / lib / pydoc.py < prev    next >
Encoding:
Python Source  |  2003-07-18  |  82.8 KB  |  2,112 lines

  1. #!/usr/bin/env python
  2. """Generate Python documentation in HTML or text for interactive use.
  3.  
  4. In the Python interpreter, do "from pydoc import help" to provide online
  5. help.  Calling help(thing) on a Python object documents the object.
  6.  
  7. Or, at the shell command line outside of Python:
  8.  
  9. Run "pydoc <name>" to show documentation on something.  <name> may be
  10. the name of a function, module, package, or a dotted reference to a
  11. class or function within a module or module in a package.  If the
  12. argument contains a path segment delimiter (e.g. slash on Unix,
  13. backslash on Windows) it is treated as the path to a Python source file.
  14.  
  15. Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
  16. of all available modules.
  17.  
  18. Run "pydoc -p <port>" to start an HTTP server on a given port on the
  19. local machine to generate documentation web pages.
  20.  
  21. For platforms without a command line, "pydoc -g" starts the HTTP server
  22. and also pops up a little window for controlling it.
  23.  
  24. Run "pydoc -w <name>" to write out the HTML documentation for a module
  25. to a file named "<name>.html".
  26. """
  27.  
  28. __author__ = "Ka-Ping Yee <ping@lfw.org>"
  29. __date__ = "26 February 2001"
  30. __version__ = "$Revision: 1.56.8.6 $"
  31. __credits__ = """Guido van Rossum, for an excellent programming language.
  32. Tommy Burnette, the original creator of manpy.
  33. Paul Prescod, for all his work on onlinehelp.
  34. Richard Chamberlain, for the first implementation of textdoc.
  35.  
  36. Mynd you, m°°se bites Kan be pretty nasti..."""
  37.  
  38. # Known bugs that can't be fixed here:
  39. #   - imp.load_module() cannot be prevented from clobbering existing
  40. #     loaded modules, so calling synopsis() on a binary module file
  41. #     changes the contents of any existing module with the same name.
  42. #   - If the __file__ attribute on a module is a relative path and
  43. #     the current directory is changed with os.chdir(), an incorrect
  44. #     path will be displayed.
  45.  
  46. import sys, imp, os, stat, re, types, inspect
  47. from repr import Repr
  48. from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
  49.  
  50. # --------------------------------------------------------- common routines
  51.  
  52. def pathdirs():
  53.     """Convert sys.path into a list of absolute, existing, unique paths."""
  54.     dirs = []
  55.     normdirs = []
  56.     for dir in sys.path:
  57.         dir = os.path.abspath(dir or '.')
  58.         normdir = os.path.normcase(dir)
  59.         if normdir not in normdirs and os.path.isdir(dir):
  60.             dirs.append(dir)
  61.             normdirs.append(normdir)
  62.     return dirs
  63.  
  64. def getdoc(object):
  65.     """Get the doc string or comments for an object."""
  66.     result = inspect.getdoc(object) or inspect.getcomments(object)
  67.     return result and re.sub('^ *\n', '', rstrip(result)) or ''
  68.  
  69. def splitdoc(doc):
  70.     """Split a doc string into a synopsis line (if any) and the rest."""
  71.     lines = split(strip(doc), '\n')
  72.     if len(lines) == 1:
  73.         return lines[0], ''
  74.     elif len(lines) >= 2 and not rstrip(lines[1]):
  75.         return lines[0], join(lines[2:], '\n')
  76.     return '', join(lines, '\n')
  77.  
  78. def classname(object, modname):
  79.     """Get a class name and qualify it with a module name if necessary."""
  80.     name = object.__name__
  81.     if object.__module__ != modname:
  82.         name = object.__module__ + '.' + name
  83.     return name
  84.  
  85. def isdata(object):
  86.     """Check if an object is of a type that probably means it's data."""
  87.     return not (inspect.ismodule(object) or inspect.isclass(object) or
  88.                 inspect.isroutine(object) or inspect.isframe(object) or
  89.                 inspect.istraceback(object) or inspect.iscode(object))
  90.  
  91. def replace(text, *pairs):
  92.     """Do a series of global replacements on a string."""
  93.     while pairs:
  94.         text = join(split(text, pairs[0]), pairs[1])
  95.         pairs = pairs[2:]
  96.     return text
  97.  
  98. def cram(text, maxlen):
  99.     """Omit part of a string if needed to make it fit in a maximum length."""
  100.     if len(text) > maxlen:
  101.         pre = max(0, (maxlen-3)/2)
  102.         post = max(0, maxlen-3-pre)
  103.         return text[:pre] + '...' + text[len(text)-post:]
  104.     return text
  105.  
  106. def stripid(text):
  107.     """Remove the hexadecimal id from a Python object representation."""
  108.     # The behaviour of %p is implementation-dependent; we check two cases.
  109.     for pattern in [' at 0x[0-9a-f]{6,}(>+)$', ' at [0-9A-F]{8,}(>+)$']:
  110.         if re.search(pattern, repr(Exception)):
  111.             return re.sub(pattern, '\\1', text)
  112.     return text
  113.  
  114. def _is_some_method(object):
  115.     return inspect.ismethod(object) or inspect.ismethoddescriptor(object)
  116.  
  117. def allmethods(cl):
  118.     methods = {}
  119.     for key, value in inspect.getmembers(cl, _is_some_method):
  120.         methods[key] = 1
  121.     for base in cl.__bases__:
  122.         methods.update(allmethods(base)) # all your base are belong to us
  123.     for key in methods.keys():
  124.         methods[key] = getattr(cl, key)
  125.     return methods
  126.  
  127. def _split_list(s, predicate):
  128.     """Split sequence s via predicate, and return pair ([true], [false]).
  129.  
  130.     The return value is a 2-tuple of lists,
  131.         ([x for x in s if predicate(x)],
  132.          [x for x in s if not predicate(x)])
  133.     """
  134.  
  135.     yes = []
  136.     no = []
  137.     for x in s:
  138.         if predicate(x):
  139.             yes.append(x)
  140.         else:
  141.             no.append(x)
  142.     return yes, no
  143.  
  144. # ----------------------------------------------------- module manipulation
  145.  
  146. def ispackage(path):
  147.     """Guess whether a path refers to a package directory."""
  148.     if os.path.isdir(path):
  149.         for ext in ['.py', '.pyc', '.pyo']:
  150.             if os.path.isfile(os.path.join(path, '__init__' + ext)):
  151.                 return 1
  152.  
  153. def synopsis(filename, cache={}):
  154.     """Get the one-line summary out of a module file."""
  155.     mtime = os.stat(filename)[stat.ST_MTIME]
  156.     lastupdate, result = cache.get(filename, (0, None))
  157.     if lastupdate < mtime:
  158.         info = inspect.getmoduleinfo(filename)
  159.         file = open(filename)
  160.         if info and 'b' in info[2]: # binary modules have to be imported
  161.             try: module = imp.load_module('__temp__', file, filename, info[1:])
  162.             except: return None
  163.             result = split(module.__doc__ or '', '\n')[0]
  164.             del sys.modules['__temp__']
  165.         else: # text modules can be directly examined
  166.             line = file.readline()
  167.             while line[:1] == '#' or not strip(line):
  168.                 line = file.readline()
  169.                 if not line: break
  170.             line = strip(line)
  171.             if line[:4] == 'r"""': line = line[1:]
  172.             if line[:3] == '"""':
  173.                 line = line[3:]
  174.                 if line[-1:] == '\\': line = line[:-1]
  175.                 while not strip(line):
  176.                     line = file.readline()
  177.                     if not line: break
  178.                 result = strip(split(line, '"""')[0])
  179.             else: result = None
  180.         file.close()
  181.         cache[filename] = (mtime, result)
  182.     return result
  183.  
  184. class ErrorDuringImport(Exception):
  185.     """Errors that occurred while trying to import something to document it."""
  186.     def __init__(self, filename, (exc, value, tb)):
  187.         self.filename = filename
  188.         self.exc = exc
  189.         self.value = value
  190.         self.tb = tb
  191.  
  192.     def __str__(self):
  193.         exc = self.exc
  194.         if type(exc) is types.ClassType:
  195.             exc = exc.__name__
  196.         return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
  197.  
  198. def importfile(path):
  199.     """Import a Python source file or compiled file given its path."""
  200.     magic = imp.get_magic()
  201.     file = open(path, 'r')
  202.     if file.read(len(magic)) == magic:
  203.         kind = imp.PY_COMPILED
  204.     else:
  205.         kind = imp.PY_SOURCE
  206.     file.close()
  207.     filename = os.path.basename(path)
  208.     name, ext = os.path.splitext(filename)
  209.     file = open(path, 'r')
  210.     try:
  211.         module = imp.load_module(name, file, path, (ext, 'r', kind))
  212.     except:
  213.         raise ErrorDuringImport(path, sys.exc_info())
  214.     file.close()
  215.     return module
  216.  
  217. def safeimport(path, forceload=0, cache={}):
  218.     """Import a module; handle errors; return None if the module isn't found.
  219.  
  220.     If the module *is* found but an exception occurs, it's wrapped in an
  221.     ErrorDuringImport exception and reraised.  Unlike __import__, if a
  222.     package path is specified, the module at the end of the path is returned,
  223.     not the package at the beginning.  If the optional 'forceload' argument
  224.     is 1, we reload the module from disk (unless it's a dynamic extension)."""
  225.     if forceload and sys.modules.has_key(path):
  226.         # This is the only way to be sure.  Checking the mtime of the file
  227.         # isn't good enough (e.g. what if the module contains a class that
  228.         # inherits from another module that has changed?).
  229.         if path not in sys.builtin_module_names:
  230.             # Python never loads a dynamic extension a second time from the
  231.             # same path, even if the file is changed or missing.  Deleting
  232.             # the entry in sys.modules doesn't help for dynamic extensions,
  233.             # so we're not even going to try to keep them up to date.
  234.             info = inspect.getmoduleinfo(sys.modules[path].__file__)
  235.             if info[3] != imp.C_EXTENSION:
  236.                 cache[path] = sys.modules[path] # prevent module from clearing
  237.                 del sys.modules[path]
  238.     try:
  239.         module = __import__(path)
  240.     except:
  241.         # Did the error occur before or after the module was found?
  242.         (exc, value, tb) = info = sys.exc_info()
  243.         if sys.modules.has_key(path):
  244.             # An error occured while executing the imported module.
  245.             raise ErrorDuringImport(sys.modules[path].__file__, info)
  246.         elif exc is SyntaxError:
  247.             # A SyntaxError occurred before we could execute the module.
  248.             raise ErrorDuringImport(value.filename, info)
  249.         elif exc is ImportError and \
  250.              split(lower(str(value)))[:2] == ['no', 'module']:
  251.             # The module was not found.
  252.             return None
  253.         else:
  254.             # Some other error occurred during the importing process.
  255.             raise ErrorDuringImport(path, sys.exc_info())
  256.     for part in split(path, '.')[1:]:
  257.         try: module = getattr(module, part)
  258.         except AttributeError: return None
  259.     return module
  260.  
  261. # ---------------------------------------------------- formatter base class
  262.  
  263. class Doc:
  264.     def document(self, object, name=None, *args):
  265.         """Generate documentation for an object."""
  266.         args = (object, name) + args
  267.         if inspect.ismodule(object): return apply(self.docmodule, args)
  268.         if inspect.isclass(object): return apply(self.docclass, args)
  269.         if inspect.isroutine(object): return apply(self.docroutine, args)
  270.         return apply(self.docother, args)
  271.  
  272.     def fail(self, object, name=None, *args):
  273.         """Raise an exception for unimplemented types."""
  274.         message = "don't know how to document object%s of type %s" % (
  275.             name and ' ' + repr(name), type(object).__name__)
  276.         raise TypeError, message
  277.  
  278.     docmodule = docclass = docroutine = docother = fail
  279.  
  280. # -------------------------------------------- HTML documentation generator
  281.  
  282. class HTMLRepr(Repr):
  283.     """Class for safely making an HTML representation of a Python object."""
  284.     def __init__(self):
  285.         Repr.__init__(self)
  286.         self.maxlist = self.maxtuple = 20
  287.         self.maxdict = 10
  288.         self.maxstring = self.maxother = 100
  289.  
  290.     def escape(self, text):
  291.         return replace(text, '&', '&', '<', '<', '>', '>')
  292.  
  293.     def repr(self, object):
  294.         return Repr.repr(self, object)
  295.  
  296.     def repr1(self, x, level):
  297.         methodname = 'repr_' + join(split(type(x).__name__), '_')
  298.         if hasattr(self, methodname):
  299.             return getattr(self, methodname)(x, level)
  300.         else:
  301.             return self.escape(cram(stripid(repr(x)), self.maxother))
  302.  
  303.     def repr_string(self, x, level):
  304.         test = cram(x, self.maxstring)
  305.         testrepr = repr(test)
  306.         if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
  307.             # Backslashes are only literal in the string and are never
  308.             # needed to make any special characters, so show a raw string.
  309.             return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
  310.         return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',
  311.                       r'<font color="#c040c0">\1</font>',
  312.                       self.escape(testrepr))
  313.  
  314.     repr_str = repr_string
  315.  
  316.     def repr_instance(self, x, level):
  317.         try:
  318.             return self.escape(cram(stripid(repr(x)), self.maxstring))
  319.         except:
  320.             return self.escape('<%s instance>' % x.__class__.__name__)
  321.  
  322.     repr_unicode = repr_string
  323.  
  324. class HTMLDoc(Doc):
  325.     """Formatter class for HTML documentation."""
  326.  
  327.     # ------------------------------------------- HTML formatting utilities
  328.  
  329.     _repr_instance = HTMLRepr()
  330.     repr = _repr_instance.repr
  331.     escape = _repr_instance.escape
  332.  
  333.     def page(self, title, contents):
  334.         """Format an HTML page."""
  335.         return '''
  336. <!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  337. <html><head><title>Python: %s</title>
  338. <style type="text/css"><!--
  339. TT { font-family: lucidatypewriter, lucida console, courier }
  340. --></style></head><body bgcolor="#f0f0f8">
  341. %s
  342. </body></html>''' % (title, contents)
  343.  
  344.     def heading(self, title, fgcol, bgcol, extras=''):
  345.         """Format a page heading."""
  346.         return '''
  347. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
  348. <tr bgcolor="%s">
  349. <td valign=bottom> <br>
  350. <font color="%s" face="helvetica, arial"> <br>%s</font></td
  351. ><td align=right valign=bottom
  352. ><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
  353.     ''' % (bgcol, fgcol, title, fgcol, extras or ' ')
  354.  
  355.     def section(self, title, fgcol, bgcol, contents, width=10,
  356.                 prelude='', marginalia=None, gap='  '):
  357.         """Format a section with a heading."""
  358.         if marginalia is None:
  359.             marginalia = '<tt>' + ' ' * width + '</tt>'
  360.         result = '''
  361. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  362. <tr bgcolor="%s">
  363. <td colspan=3 valign=bottom> <br>
  364. <font color="%s" face="helvetica, arial">%s</font></td></tr>
  365.     ''' % (bgcol, fgcol, title)
  366.         if prelude:
  367.             result = result + '''
  368. <tr bgcolor="%s"><td rowspan=2>%s</td>
  369. <td colspan=2>%s</td></tr>
  370. <tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)
  371.         else:
  372.             result = result + '''
  373. <tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)
  374.  
  375.         return result + '\n<td width="100%%">%s</td></tr></table>' % contents
  376.  
  377.     def bigsection(self, title, *args):
  378.         """Format a section with a big heading."""
  379.         title = '<big><strong>%s</strong></big>' % title
  380.         return apply(self.section, (title,) + args)
  381.  
  382.     def preformat(self, text):
  383.         """Format literal preformatted text."""
  384.         text = self.escape(expandtabs(text))
  385.         return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
  386.                              ' ', ' ', '\n', '<br>\n')
  387.  
  388.     def multicolumn(self, list, format, cols=4):
  389.         """Format a list of items into a multi-column list."""
  390.         result = ''
  391.         rows = (len(list)+cols-1)/cols
  392.         for col in range(cols):
  393.             result = result + '<td width="%d%%" valign=top>' % (100/cols)
  394.             for i in range(rows*col, rows*col+rows):
  395.                 if i < len(list):
  396.                     result = result + format(list[i]) + '<br>\n'
  397.             result = result + '</td>'
  398.         return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
  399.  
  400.     def grey(self, text): return '<font color="#909090">%s</font>' % text
  401.  
  402.     def namelink(self, name, *dicts):
  403.         """Make a link for an identifier, given name-to-URL mappings."""
  404.         for dict in dicts:
  405.             if dict.has_key(name):
  406.                 return '<a href="%s">%s</a>' % (dict[name], name)
  407.         return name
  408.  
  409.     def classlink(self, object, modname):
  410.         """Make a link for a class."""
  411.         name, module = object.__name__, sys.modules.get(object.__module__)
  412.         if hasattr(module, name) and getattr(module, name) is object:
  413.             return '<a href="%s.html#%s">%s</a>' % (
  414.                 module.__name__, name, classname(object, modname))
  415.         return classname(object, modname)
  416.  
  417.     def modulelink(self, object):
  418.         """Make a link for a module."""
  419.         return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
  420.  
  421.     def modpkglink(self, (name, path, ispackage, shadowed)):
  422.         """Make a link for a module or package to display in an index."""
  423.         if shadowed:
  424.             return self.grey(name)
  425.         if path:
  426.             url = '%s.%s.html' % (path, name)
  427.         else:
  428.             url = '%s.html' % name
  429.         if ispackage:
  430.             text = '<strong>%s</strong> (package)' % name
  431.         else:
  432.             text = name
  433.         return '<a href="%s">%s</a>' % (url, text)
  434.  
  435.     def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
  436.         """Mark up some plain text, given a context of symbols to look for.
  437.         Each context dictionary maps object names to anchor names."""
  438.         escape = escape or self.escape
  439.         results = []
  440.         here = 0
  441.         pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
  442.                                 r'RFC[- ]?(\d+)|'
  443.                                 r'PEP[- ]?(\d+)|'
  444.                                 r'(self\.)?(\w+))')
  445.         while 1:
  446.             match = pattern.search(text, here)
  447.             if not match: break
  448.             start, end = match.span()
  449.             results.append(escape(text[here:start]))
  450.  
  451.             all, scheme, rfc, pep, selfdot, name = match.groups()
  452.             if scheme:
  453.                 url = escape(all).replace('"', '"')
  454.                 results.append('<a href="%s">%s</a>' % (url, url))
  455.             elif rfc:
  456.                 url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
  457.                 results.append('<a href="%s">%s</a>' % (url, escape(all)))
  458.             elif pep:
  459.                 url = 'http://www.python.org/peps/pep-%04d.html' % int(pep)
  460.                 results.append('<a href="%s">%s</a>' % (url, escape(all)))
  461.             elif text[end:end+1] == '(':
  462.                 results.append(self.namelink(name, methods, funcs, classes))
  463.             elif selfdot:
  464.                 results.append('self.<strong>%s</strong>' % name)
  465.             else:
  466.                 results.append(self.namelink(name, classes))
  467.             here = end
  468.         results.append(escape(text[here:]))
  469.         return join(results, '')
  470.  
  471.     # ---------------------------------------------- type-specific routines
  472.  
  473.     def formattree(self, tree, modname, parent=None):
  474.         """Produce HTML for a class tree as given by inspect.getclasstree()."""
  475.         result = ''
  476.         for entry in tree:
  477.             if type(entry) is type(()):
  478.                 c, bases = entry
  479.                 result = result + '<dt><font face="helvetica, arial">'
  480.                 result = result + self.classlink(c, modname)
  481.                 if bases and bases != (parent,):
  482.                     parents = []
  483.                     for base in bases:
  484.                         parents.append(self.classlink(base, modname))
  485.                     result = result + '(' + join(parents, ', ') + ')'
  486.                 result = result + '\n</font></dt>'
  487.             elif type(entry) is type([]):
  488.                 result = result + '<dd>\n%s</dd>\n' % self.formattree(
  489.                     entry, modname, c)
  490.         return '<dl>\n%s</dl>\n' % result
  491.  
  492.     def docmodule(self, object, name=None, mod=None, *ignored):
  493.         """Produce HTML documentation for a module object."""
  494.         name = object.__name__ # ignore the passed-in name
  495.         parts = split(name, '.')
  496.         links = []
  497.         for i in range(len(parts)-1):
  498.             links.append(
  499.                 '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
  500.                 (join(parts[:i+1], '.'), parts[i]))
  501.         linkedname = join(links + parts[-1:], '.')
  502.         head = '<big><big><strong>%s</strong></big></big>' % linkedname
  503.         try:
  504.             path = inspect.getabsfile(object)
  505.             url = path
  506.             if sys.platform == 'win32':
  507.                 import nturl2path
  508.                 url = nturl2path.pathname2url(path)
  509.             filelink = '<a href="file:%s">%s</a>' % (url, path)
  510.         except TypeError:
  511.             filelink = '(built-in)'
  512.         info = []
  513.         if hasattr(object, '__version__'):
  514.             version = str(object.__version__)
  515.             if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
  516.                 version = strip(version[11:-1])
  517.             info.append('version %s' % self.escape(version))
  518.         if hasattr(object, '__date__'):
  519.             info.append(self.escape(str(object.__date__)))
  520.         if info:
  521.             head = head + ' (%s)' % join(info, ', ')
  522.         result = self.heading(
  523.             head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink)
  524.  
  525.         modules = inspect.getmembers(object, inspect.ismodule)
  526.  
  527.         classes, cdict = [], {}
  528.         for key, value in inspect.getmembers(object, inspect.isclass):
  529.             if (inspect.getmodule(value) or object) is object:
  530.                 classes.append((key, value))
  531.                 cdict[key] = cdict[value] = '#' + key
  532.         for key, value in classes:
  533.             for base in value.__bases__:
  534.                 key, modname = base.__name__, base.__module__
  535.                 module = sys.modules.get(modname)
  536.                 if modname != name and module and hasattr(module, key):
  537.                     if getattr(module, key) is base:
  538.                         if not cdict.has_key(key):
  539.                             cdict[key] = cdict[base] = modname + '.html#' + key
  540.         funcs, fdict = [], {}
  541.         for key, value in inspect.getmembers(object, inspect.isroutine):
  542.             if inspect.isbuiltin(value) or inspect.getmodule(value) is object:
  543.                 funcs.append((key, value))
  544.                 fdict[key] = '#-' + key
  545.                 if inspect.isfunction(value): fdict[value] = fdict[key]
  546.         data = []
  547.         for key, value in inspect.getmembers(object, isdata):
  548.             if key not in ['__builtins__', '__doc__']:
  549.                 data.append((key, value))
  550.  
  551.         doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
  552.         doc = doc and '<tt>%s</tt>' % doc
  553.         result = result + '<p>%s</p>\n' % doc
  554.  
  555.         if hasattr(object, '__path__'):
  556.             modpkgs = []
  557.             modnames = []
  558.             for file in os.listdir(object.__path__[0]):
  559.                 path = os.path.join(object.__path__[0], file)
  560.                 modname = inspect.getmodulename(file)
  561.                 if modname and modname not in modnames:
  562.                     modpkgs.append((modname, name, 0, 0))
  563.                     modnames.append(modname)
  564.                 elif ispackage(path):
  565.                     modpkgs.append((file, name, 1, 0))
  566.             modpkgs.sort()
  567.             contents = self.multicolumn(modpkgs, self.modpkglink)
  568.             result = result + self.bigsection(
  569.                 'Package Contents', '#ffffff', '#aa55cc', contents)
  570.         elif modules:
  571.             contents = self.multicolumn(
  572.                 modules, lambda (key, value), s=self: s.modulelink(value))
  573.             result = result + self.bigsection(
  574.                 'Modules', '#fffff', '#aa55cc', contents)
  575.  
  576.         if classes:
  577.             classlist = map(lambda (key, value): value, classes)
  578.             contents = [
  579.                 self.formattree(inspect.getclasstree(classlist, 1), name)]
  580.             for key, value in classes:
  581.                 contents.append(self.document(value, key, name, fdict, cdict))
  582.             result = result + self.bigsection(
  583.                 'Classes', '#ffffff', '#ee77aa', join(contents))
  584.         if funcs:
  585.             contents = []
  586.             for key, value in funcs:
  587.                 contents.append(self.document(value, key, name, fdict, cdict))
  588.             result = result + self.bigsection(
  589.                 'Functions', '#ffffff', '#eeaa77', join(contents))
  590.         if data:
  591.             contents = []
  592.             for key, value in data:
  593.                 contents.append(self.document(value, key))
  594.             result = result + self.bigsection(
  595.                 'Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
  596.         if hasattr(object, '__author__'):
  597.             contents = self.markup(str(object.__author__), self.preformat)
  598.             result = result + self.bigsection(
  599.                 'Author', '#ffffff', '#7799ee', contents)
  600.         if hasattr(object, '__credits__'):
  601.             contents = self.markup(str(object.__credits__), self.preformat)
  602.             result = result + self.bigsection(
  603.                 'Credits', '#ffffff', '#7799ee', contents)
  604.  
  605.         return result
  606.  
  607.     def docclass(self, object, name=None, mod=None, funcs={}, classes={},
  608.                  *ignored):
  609.         """Produce HTML documentation for a class object."""
  610.         realname = object.__name__
  611.         name = name or realname
  612.         bases = object.__bases__
  613.  
  614.         contents = []
  615.         push = contents.append
  616.  
  617.         # Cute little class to pump out a horizontal rule between sections.
  618.         class HorizontalRule:
  619.             def __init__(self):
  620.                 self.needone = 0
  621.             def maybe(self):
  622.                 if self.needone:
  623.                     push('<hr>\n')
  624.                 self.needone = 1
  625.         hr = HorizontalRule()
  626.  
  627.         # List the mro, if non-trivial.
  628.         mro = list(inspect.getmro(object))
  629.         if len(mro) > 2:
  630.             hr.maybe()
  631.             push('<dl><dt>Method resolution order:</dt>\n')
  632.             for base in mro:
  633.                 push('<dd>%s</dd>\n' % self.classlink(base,
  634.                                                       object.__module__))
  635.             push('</dl>\n')
  636.  
  637.         def spill(msg, attrs, predicate):
  638.             ok, attrs = _split_list(attrs, predicate)
  639.             if ok:
  640.                 hr.maybe()
  641.                 push(msg)
  642.                 for name, kind, homecls, value in ok:
  643.                     push(self.document(getattr(object, name), name, mod,
  644.                                        funcs, classes, mdict, object))
  645.                     push('\n')
  646.             return attrs
  647.  
  648.         def spillproperties(msg, attrs, predicate):
  649.             ok, attrs = _split_list(attrs, predicate)
  650.             if ok:
  651.                 hr.maybe()
  652.                 push(msg)
  653.                 for name, kind, homecls, value in ok:
  654.                     push('<dl><dt><strong>%s</strong></dt>\n' % name)
  655.                     if value.__doc__ is not None:
  656.                         doc = self.markup(value.__doc__, self.preformat,
  657.                                           funcs, classes, mdict)
  658.                         push('<dd><tt>%s</tt></dd>\n' % doc)
  659.                     for attr, tag in [("fget", " getter"),
  660.                                       ("fset", " setter"),
  661.                                       ("fdel", " deleter")]:
  662.                         func = getattr(value, attr)
  663.                         if func is not None:
  664.                             base = self.document(func, name + tag, mod,
  665.                                                  funcs, classes, mdict, object)
  666.                             push('<dd>%s</dd>\n' % base)
  667.                     push('</dl>\n')
  668.             return attrs
  669.  
  670.         def spilldata(msg, attrs, predicate):
  671.             ok, attrs = _split_list(attrs, predicate)
  672.             if ok:
  673.                 hr.maybe()
  674.                 push(msg)
  675.                 for name, kind, homecls, value in ok:
  676.                     base = self.docother(getattr(object, name), name, mod)
  677.                     if callable(value):
  678.                         doc = getattr(value, "__doc__", None)
  679.                     else:
  680.                         doc = None
  681.                     if doc is None:
  682.                         push('<dl><dt>%s</dl>\n' % base)
  683.                     else:
  684.                         doc = self.markup(getdoc(value), self.preformat,
  685.                                           funcs, classes, mdict)
  686.                         doc = '<dd><tt>%s</tt>' % doc
  687.                         push('<dl><dt>%s%s</dl>\n' % (base, doc))
  688.                     push('\n')
  689.             return attrs
  690.  
  691.         attrs = inspect.classify_class_attrs(object)
  692.         mdict = {}
  693.         for key, kind, homecls, value in attrs:
  694.             mdict[key] = anchor = '#' + name + '-' + key
  695.             value = getattr(object, key)
  696.             try:
  697.                 # The value may not be hashable (e.g., a data attr with
  698.                 # a dict or list value).
  699.                 mdict[value] = anchor
  700.             except TypeError:
  701.                 pass
  702.  
  703.         while attrs:
  704.             if mro:
  705.                 thisclass = mro.pop(0)
  706.             else:
  707.                 thisclass = attrs[0][2]
  708.             attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
  709.  
  710.             if thisclass is object:
  711.                 tag = "defined here"
  712.             else:
  713.                 tag = "inherited from %s" % self.classlink(thisclass,
  714.                                                           object.__module__)
  715.             tag += ':<br>\n'
  716.  
  717.             # Sort attrs by name.
  718.             attrs.sort(lambda t1, t2: cmp(t1[0], t2[0]))
  719.  
  720.             # Pump out the attrs, segregated by kind.
  721.             attrs = spill("Methods %s" % tag, attrs,
  722.                           lambda t: t[1] == 'method')
  723.             attrs = spill("Class methods %s" % tag, attrs,
  724.                           lambda t: t[1] == 'class method')
  725.             attrs = spill("Static methods %s" % tag, attrs,
  726.                           lambda t: t[1] == 'static method')
  727.             attrs = spillproperties("Properties %s" % tag, attrs,
  728.                                     lambda t: t[1] == 'property')
  729.             attrs = spilldata("Data and non-method functions %s" % tag, attrs,
  730.                               lambda t: t[1] == 'data')
  731.             assert attrs == []
  732.             attrs = inherited
  733.  
  734.         contents = ''.join(contents)
  735.  
  736.         if name == realname:
  737.             title = '<a name="%s">class <strong>%s</strong></a>' % (
  738.                 name, realname)
  739.         else:
  740.             title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (
  741.                 name, name, realname)
  742.         if bases:
  743.             parents = []
  744.             for base in bases:
  745.                 parents.append(self.classlink(base, object.__module__))
  746.             title = title + '(%s)' % join(parents, ', ')
  747.         doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)
  748.         doc = doc and '<tt>%s<br> </tt>' % doc or ' '
  749.  
  750.         return self.section(title, '#000000', '#ffc8d8', contents, 5, doc)
  751.  
  752.     def formatvalue(self, object):
  753.         """Format an argument default value as text."""
  754.         return self.grey('=' + self.repr(object))
  755.  
  756.     def docroutine(self, object, name=None, mod=None,
  757.                    funcs={}, classes={}, methods={}, cl=None):
  758.         """Produce HTML documentation for a function or method object."""
  759.         realname = object.__name__
  760.         name = name or realname
  761.         anchor = (cl and cl.__name__ or '') + '-' + name
  762.         note = ''
  763.         skipdocs = 0
  764.         if inspect.ismethod(object):
  765.             imclass = object.im_class
  766.             if cl:
  767.                 if imclass is not cl:
  768.                     note = ' from ' + self.classlink(imclass, mod)
  769.             else:
  770.                 if object.im_self:
  771.                     note = ' method of %s instance' % self.classlink(
  772.                         object.im_self.__class__, mod)
  773.                 else:
  774.                     note = ' unbound %s method' % self.classlink(imclass,mod)
  775.             object = object.im_func
  776.  
  777.         if name == realname:
  778.             title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
  779.         else:
  780.             if (cl and cl.__dict__.has_key(realname) and
  781.                 cl.__dict__[realname] is object):
  782.                 reallink = '<a href="#%s">%s</a>' % (
  783.                     cl.__name__ + '-' + realname, realname)
  784.                 skipdocs = 1
  785.             else:
  786.                 reallink = realname
  787.             title = '<a name="%s"><strong>%s</strong></a> = %s' % (
  788.                 anchor, name, reallink)
  789.         if inspect.isfunction(object):
  790.             args, varargs, varkw, defaults = inspect.getargspec(object)
  791.             argspec = inspect.formatargspec(
  792.                 args, varargs, varkw, defaults, formatvalue=self.formatvalue)
  793.             if realname == '<lambda>':
  794.                 title = '<strong>%s</strong> <em>lambda</em> ' % name
  795.                 argspec = argspec[1:-1] # remove parentheses
  796.         else:
  797.             argspec = '(...)'
  798.  
  799.         decl = title + argspec + (note and self.grey(
  800.                '<font face="helvetica, arial">%s</font>' % note))
  801.  
  802.         if skipdocs:
  803.             return '<dl><dt>%s</dt></dl>\n' % decl
  804.         else:
  805.             doc = self.markup(
  806.                 getdoc(object), self.preformat, funcs, classes, methods)
  807.             doc = doc and '<dd><tt>%s</tt></dd>' % doc
  808.             return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
  809.  
  810.     def docother(self, object, name=None, mod=None, *ignored):
  811.         """Produce HTML documentation for a data object."""
  812.         lhs = name and '<strong>%s</strong> = ' % name or ''
  813.         return lhs + self.repr(object)
  814.  
  815.     def index(self, dir, shadowed=None):
  816.         """Generate an HTML index for a directory of modules."""
  817.         modpkgs = []
  818.         if shadowed is None: shadowed = {}
  819.         seen = {}
  820.         files = os.listdir(dir)
  821.  
  822.         def found(name, ispackage,
  823.                   modpkgs=modpkgs, shadowed=shadowed, seen=seen):
  824.             if not seen.has_key(name):
  825.                 modpkgs.append((name, '', ispackage, shadowed.has_key(name)))
  826.                 seen[name] = 1
  827.                 shadowed[name] = 1
  828.  
  829.         # Package spam/__init__.py takes precedence over module spam.py.
  830.         for file in files:
  831.             path = os.path.join(dir, file)
  832.             if ispackage(path): found(file, 1)
  833.         for file in files:
  834.             path = os.path.join(dir, file)
  835.             if os.path.isfile(path):
  836.                 modname = inspect.getmodulename(file)
  837.                 if modname: found(modname, 0)
  838.  
  839.         modpkgs.sort()
  840.         contents = self.multicolumn(modpkgs, self.modpkglink)
  841.         return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
  842.  
  843. # -------------------------------------------- text documentation generator
  844.  
  845. class TextRepr(Repr):
  846.     """Class for safely making a text representation of a Python object."""
  847.     def __init__(self):
  848.         Repr.__init__(self)
  849.         self.maxlist = self.maxtuple = 20
  850.         self.maxdict = 10
  851.         self.maxstring = self.maxother = 100
  852.  
  853.     def repr1(self, x, level):
  854.         methodname = 'repr_' + join(split(type(x).__name__), '_')
  855.         if hasattr(self, methodname):
  856.             return getattr(self, methodname)(x, level)
  857.         else:
  858.             return cram(stripid(repr(x)), self.maxother)
  859.  
  860.     def repr_string(self, x, level):
  861.         test = cram(x, self.maxstring)
  862.         testrepr = repr(test)
  863.         if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
  864.             # Backslashes are only literal in the string and are never
  865.             # needed to make any special characters, so show a raw string.
  866.             return 'r' + testrepr[0] + test + testrepr[0]
  867.         return testrepr
  868.  
  869.     repr_str = repr_string
  870.  
  871.     def repr_instance(self, x, level):
  872.         try:
  873.             return cram(stripid(repr(x)), self.maxstring)
  874.         except:
  875.             return '<%s instance>' % x.__class__.__name__
  876.  
  877. class TextDoc(Doc):
  878.     """Formatter class for text documentation."""
  879.  
  880.     # ------------------------------------------- text formatting utilities
  881.  
  882.     _repr_instance = TextRepr()
  883.     repr = _repr_instance.repr
  884.  
  885.     def bold(self, text):
  886.         """Format a string in bold by overstriking."""
  887.         return join(map(lambda ch: ch + '\b' + ch, text), '')
  888.  
  889.     def indent(self, text, prefix='    '):
  890.         """Indent text by prepending a given prefix to each line."""
  891.         if not text: return ''
  892.         lines = split(text, '\n')
  893.         lines = map(lambda line, prefix=prefix: prefix + line, lines)
  894.         if lines: lines[-1] = rstrip(lines[-1])
  895.         return join(lines, '\n')
  896.  
  897.     def section(self, title, contents):
  898.         """Format a section with a given heading."""
  899.         return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
  900.  
  901.     # ---------------------------------------------- type-specific routines
  902.  
  903.     def formattree(self, tree, modname, parent=None, prefix=''):
  904.         """Render in text a class tree as returned by inspect.getclasstree()."""
  905.         result = ''
  906.         for entry in tree:
  907.             if type(entry) is type(()):
  908.                 c, bases = entry
  909.                 result = result + prefix + classname(c, modname)
  910.                 if bases and bases != (parent,):
  911.                     parents = map(lambda c, m=modname: classname(c, m), bases)
  912.                     result = result + '(%s)' % join(parents, ', ')
  913.                 result = result + '\n'
  914.             elif type(entry) is type([]):
  915.                 result = result + self.formattree(
  916.                     entry, modname, c, prefix + '    ')
  917.         return result
  918.  
  919.     def docmodule(self, object, name=None, mod=None):
  920.         """Produce text documentation for a given module object."""
  921.         name = object.__name__ # ignore the passed-in name
  922.         synop, desc = splitdoc(getdoc(object))
  923.         result = self.section('NAME', name + (synop and ' - ' + synop))
  924.  
  925.         try:
  926.             file = inspect.getabsfile(object)
  927.         except TypeError:
  928.             file = '(built-in)'
  929.         result = result + self.section('FILE', file)
  930.         if desc:
  931.             result = result + self.section('DESCRIPTION', desc)
  932.  
  933.         classes = []
  934.         for key, value in inspect.getmembers(object, inspect.isclass):
  935.             if (inspect.getmodule(value) or object) is object:
  936.                 classes.append((key, value))
  937.         funcs = []
  938.         for key, value in inspect.getmembers(object, inspect.isroutine):
  939.             if inspect.isbuiltin(value) or inspect.getmodule(value) is object:
  940.                 funcs.append((key, value))
  941.         data = []
  942.         for key, value in inspect.getmembers(object, isdata):
  943.             if key not in ['__builtins__', '__doc__']:
  944.                 data.append((key, value))
  945.  
  946.         if hasattr(object, '__path__'):
  947.             modpkgs = []
  948.             for file in os.listdir(object.__path__[0]):
  949.                 path = os.path.join(object.__path__[0], file)
  950.                 modname = inspect.getmodulename(file)
  951.                 if modname and modname not in modpkgs:
  952.                     modpkgs.append(modname)
  953.                 elif ispackage(path):
  954.                     modpkgs.append(file + ' (package)')
  955.             modpkgs.sort()
  956.             result = result + self.section(
  957.                 'PACKAGE CONTENTS', join(modpkgs, '\n'))
  958.  
  959.         if classes:
  960.             classlist = map(lambda (key, value): value, classes)
  961.             contents = [self.formattree(
  962.                 inspect.getclasstree(classlist, 1), name)]
  963.             for key, value in classes:
  964.                 contents.append(self.document(value, key, name))
  965.             result = result + self.section('CLASSES', join(contents, '\n'))
  966.  
  967.         if funcs:
  968.             contents = []
  969.             for key, value in funcs:
  970.                 contents.append(self.document(value, key, name))
  971.             result = result + self.section('FUNCTIONS', join(contents, '\n'))
  972.  
  973.         if data:
  974.             contents = []
  975.             for key, value in data:
  976.                 contents.append(self.docother(value, key, name, 70))
  977.             result = result + self.section('DATA', join(contents, '\n'))
  978.  
  979.         if hasattr(object, '__version__'):
  980.             version = str(object.__version__)
  981.             if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
  982.                 version = strip(version[11:-1])
  983.             result = result + self.section('VERSION', version)
  984.         if hasattr(object, '__date__'):
  985.             result = result + self.section('DATE', str(object.__date__))
  986.         if hasattr(object, '__author__'):
  987.             result = result + self.section('AUTHOR', str(object.__author__))
  988.         if hasattr(object, '__credits__'):
  989.             result = result + self.section('CREDITS', str(object.__credits__))
  990.         return result
  991.  
  992.     def docclass(self, object, name=None, mod=None):
  993.         """Produce text documentation for a given class object."""
  994.         realname = object.__name__
  995.         name = name or realname
  996.         bases = object.__bases__
  997.  
  998.         def makename(c, m=object.__module__):
  999.             return classname(c, m)
  1000.  
  1001.         if name == realname:
  1002.             title = 'class ' + self.bold(realname)
  1003.         else:
  1004.             title = self.bold(name) + ' = class ' + realname
  1005.         if bases:
  1006.             parents = map(makename, bases)
  1007.             title = title + '(%s)' % join(parents, ', ')
  1008.  
  1009.         doc = getdoc(object)
  1010.         contents = doc and [doc + '\n'] or []
  1011.         push = contents.append
  1012.  
  1013.         # List the mro, if non-trivial.
  1014.         mro = list(inspect.getmro(object))
  1015.         if len(mro) > 2:
  1016.             push("Method resolution order:")
  1017.             for base in mro:
  1018.                 push('    ' + makename(base))
  1019.             push('')
  1020.  
  1021.         # Cute little class to pump out a horizontal rule between sections.
  1022.         class HorizontalRule:
  1023.             def __init__(self):
  1024.                 self.needone = 0
  1025.             def maybe(self):
  1026.                 if self.needone:
  1027.                     push('-' * 70)
  1028.                 self.needone = 1
  1029.         hr = HorizontalRule()
  1030.  
  1031.         def spill(msg, attrs, predicate):
  1032.             ok, attrs = _split_list(attrs, predicate)
  1033.             if ok:
  1034.                 hr.maybe()
  1035.                 push(msg)
  1036.                 for name, kind, homecls, value in ok:
  1037.                     push(self.document(getattr(object, name),
  1038.                                        name, mod, object))
  1039.             return attrs
  1040.  
  1041.         def spillproperties(msg, attrs, predicate):
  1042.             ok, attrs = _split_list(attrs, predicate)
  1043.             if ok:
  1044.                 hr.maybe()
  1045.                 push(msg)
  1046.                 for name, kind, homecls, value in ok:
  1047.                     push(name)
  1048.                     need_blank_after_doc = 0
  1049.                     doc = getdoc(value) or ''
  1050.                     if doc:
  1051.                         push(self.indent(doc))
  1052.                         need_blank_after_doc = 1
  1053.                     for attr, tag in [("fget", " getter"),
  1054.                                       ("fset", " setter"),
  1055.                                       ("fdel", " deleter")]:
  1056.                         func = getattr(value, attr)
  1057.                         if func is not None:
  1058.                             if need_blank_after_doc:
  1059.                                 push('')
  1060.                                 need_blank_after_doc = 0
  1061.                             base = self.docother(func, name + tag, mod, 70)
  1062.                             push(self.indent(base))
  1063.                     push('')
  1064.             return attrs
  1065.  
  1066.         def spilldata(msg, attrs, predicate):
  1067.             ok, attrs = _split_list(attrs, predicate)
  1068.             if ok:
  1069.                 hr.maybe()
  1070.                 push(msg)
  1071.                 for name, kind, homecls, value in ok:
  1072.                     if callable(value):
  1073.                         doc = getattr(value, "__doc__", None)
  1074.                     else:
  1075.                         doc = None
  1076.                     push(self.docother(getattr(object, name),
  1077.                                        name, mod, 70, doc) + '\n')
  1078.             return attrs
  1079.  
  1080.         attrs = inspect.classify_class_attrs(object)
  1081.         while attrs:
  1082.             if mro:
  1083.                 thisclass = mro.pop(0)
  1084.             else:
  1085.                 thisclass = attrs[0][2]
  1086.             attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
  1087.  
  1088.             if thisclass is object:
  1089.                 tag = "defined here"
  1090.             else:
  1091.                 tag = "inherited from %s" % classname(thisclass,
  1092.                                                       object.__module__)
  1093.  
  1094.             # Sort attrs by name.
  1095.             attrs.sort(lambda t1, t2: cmp(t1[0], t2[0]))
  1096.  
  1097.             # Pump out the attrs, segregated by kind.
  1098.             attrs = spill("Methods %s:\n" % tag, attrs,
  1099.                           lambda t: t[1] == 'method')
  1100.             attrs = spill("Class methods %s:\n" % tag, attrs,
  1101.                           lambda t: t[1] == 'class method')
  1102.             attrs = spill("Static methods %s:\n" % tag, attrs,
  1103.                           lambda t: t[1] == 'static method')
  1104.             attrs = spillproperties("Properties %s:\n" % tag, attrs,
  1105.                                     lambda t: t[1] == 'property')
  1106.             attrs = spilldata("Data and non-method functions %s:\n" % tag,
  1107.                               attrs, lambda t: t[1] == 'data')
  1108.             assert attrs == []
  1109.             attrs = inherited
  1110.  
  1111.         contents = '\n'.join(contents)
  1112.         if not contents:
  1113.             return title + '\n'
  1114.         return title + '\n' + self.indent(rstrip(contents), ' |  ') + '\n'
  1115.  
  1116.     def formatvalue(self, object):
  1117.         """Format an argument default value as text."""
  1118.         return '=' + self.repr(object)
  1119.  
  1120.     def docroutine(self, object, name=None, mod=None, cl=None):
  1121.         """Produce text documentation for a function or method object."""
  1122.         realname = object.__name__
  1123.         name = name or realname
  1124.         note = ''
  1125.         skipdocs = 0
  1126.         if inspect.ismethod(object):
  1127.             imclass = object.im_class
  1128.             if cl:
  1129.                 if imclass is not cl:
  1130.                     note = ' from ' + classname(imclass, mod)
  1131.             else:
  1132.                 if object.im_self:
  1133.                     note = ' method of %s instance' % classname(
  1134.                         object.im_self.__class__, mod)
  1135.                 else:
  1136.                     note = ' unbound %s method' % classname(imclass,mod)
  1137.             object = object.im_func
  1138.  
  1139.         if name == realname:
  1140.             title = self.bold(realname)
  1141.         else:
  1142.             if (cl and cl.__dict__.has_key(realname) and
  1143.                 cl.__dict__[realname] is object):
  1144.                 skipdocs = 1
  1145.             title = self.bold(name) + ' = ' + realname
  1146.         if inspect.isfunction(object):
  1147.             args, varargs, varkw, defaults = inspect.getargspec(object)
  1148.             argspec = inspect.formatargspec(
  1149.                 args, varargs, varkw, defaults, formatvalue=self.formatvalue)
  1150.             if realname == '<lambda>':
  1151.                 title = 'lambda'
  1152.                 argspec = argspec[1:-1] # remove parentheses
  1153.         else:
  1154.             argspec = '(...)'
  1155.         decl = title + argspec + note
  1156.  
  1157.         if skipdocs:
  1158.             return decl + '\n'
  1159.         else:
  1160.             doc = getdoc(object) or ''
  1161.             return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n')
  1162.  
  1163.     def docother(self, object, name=None, mod=None, maxlen=None, doc=None):
  1164.         """Produce text documentation for a data object."""
  1165.         repr = self.repr(object)
  1166.         if maxlen:
  1167.             line = (name and name + ' = ' or '') + repr
  1168.             chop = maxlen - len(line)
  1169.             if chop < 0: repr = repr[:chop] + '...'
  1170.         line = (name and self.bold(name) + ' = ' or '') + repr
  1171.         if doc is not None:
  1172.             line += '\n' + self.indent(str(doc))
  1173.         return line
  1174.  
  1175. # --------------------------------------------------------- user interfaces
  1176.  
  1177. def pager(text):
  1178.     """The first time this is called, determine what kind of pager to use."""
  1179.     global pager
  1180.     pager = getpager()
  1181.     pager(text)
  1182.  
  1183. def getpager():
  1184.     """Decide what method to use for paging through text."""
  1185.     if type(sys.stdout) is not types.FileType:
  1186.         return plainpager
  1187.     if not sys.stdin.isatty() or not sys.stdout.isatty():
  1188.         return plainpager
  1189.     if os.environ.get('TERM') in ['dumb', 'emacs']:
  1190.         return plainpager
  1191.     if os.environ.has_key('PAGER'):
  1192.         if sys.platform == 'win32': # pipes completely broken in Windows
  1193.             return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
  1194.         elif os.environ.get('TERM') in ['dumb', 'emacs']:
  1195.             return lambda text: pipepager(plain(text), os.environ['PAGER'])
  1196.         else:
  1197.             return lambda text: pipepager(text, os.environ['PAGER'])
  1198.     if sys.platform == 'win32':
  1199.         return lambda text: tempfilepager(plain(text), 'more <')
  1200.     if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
  1201.         return lambda text: pipepager(text, 'less')
  1202.  
  1203.     import tempfile
  1204.     filename = tempfile.mktemp()
  1205.     open(filename, 'w').close()
  1206.     try:
  1207.         if hasattr(os, 'system') and os.system('more %s' % filename) == 0:
  1208.             return lambda text: pipepager(text, 'more')
  1209.         else:
  1210.             return ttypager
  1211.     finally:
  1212.         os.unlink(filename)
  1213.  
  1214. def plain(text):
  1215.     """Remove boldface formatting from text."""
  1216.     return re.sub('.\b', '', text)
  1217.  
  1218. def pipepager(text, cmd):
  1219.     """Page through text by feeding it to another program."""
  1220.     pipe = os.popen(cmd, 'w')
  1221.     try:
  1222.         pipe.write(text)
  1223.         pipe.close()
  1224.     except IOError:
  1225.         pass # Ignore broken pipes caused by quitting the pager program.
  1226.  
  1227. def tempfilepager(text, cmd):
  1228.     """Page through text by invoking a program on a temporary file."""
  1229.     import tempfile
  1230.     filename = tempfile.mktemp()
  1231.     file = open(filename, 'w')
  1232.     file.write(text)
  1233.     file.close()
  1234.     try:
  1235.         os.system(cmd + ' ' + filename)
  1236.     finally:
  1237.         os.unlink(filename)
  1238.  
  1239. def ttypager(text):
  1240.     """Page through text on a text terminal."""
  1241.     lines = split(plain(text), '\n')
  1242.     try:
  1243.         import tty
  1244.         fd = sys.stdin.fileno()
  1245.         old = tty.tcgetattr(fd)
  1246.         tty.setcbreak(fd)
  1247.         getchar = lambda: sys.stdin.read(1)
  1248.     except (ImportError, AttributeError):
  1249.         tty = None
  1250.         getchar = lambda: sys.stdin.readline()[:-1][:1]
  1251.  
  1252.     try:
  1253.         r = inc = os.environ.get('LINES', 25) - 1
  1254.         sys.stdout.write(join(lines[:inc], '\n') + '\n')
  1255.         while lines[r:]:
  1256.             sys.stdout.write('-- more --')
  1257.             sys.stdout.flush()
  1258.             c = getchar()
  1259.  
  1260.             if c in ['q', 'Q']:
  1261.                 sys.stdout.write('\r          \r')
  1262.                 break
  1263.             elif c in ['\r', '\n']:
  1264.                 sys.stdout.write('\r          \r' + lines[r] + '\n')
  1265.                 r = r + 1
  1266.                 continue
  1267.             if c in ['b', 'B', '\x1b']:
  1268.                 r = r - inc - inc
  1269.                 if r < 0: r = 0
  1270.             sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
  1271.             r = r + inc
  1272.  
  1273.     finally:
  1274.         if tty:
  1275.             tty.tcsetattr(fd, tty.TCSAFLUSH, old)
  1276.  
  1277. def plainpager(text):
  1278.     """Simply print unformatted text.  This is the ultimate fallback."""
  1279.     sys.stdout.write(plain(text))
  1280.  
  1281. def describe(thing):
  1282.     """Produce a short description of the given thing."""
  1283.     if inspect.ismodule(thing):
  1284.         if thing.__name__ in sys.builtin_module_names:
  1285.             return 'built-in module ' + thing.__name__
  1286.         if hasattr(thing, '__path__'):
  1287.             return 'package ' + thing.__name__
  1288.         else:
  1289.             return 'module ' + thing.__name__
  1290.     if inspect.isbuiltin(thing):
  1291.         return 'built-in function ' + thing.__name__
  1292.     if inspect.isclass(thing):
  1293.         return 'class ' + thing.__name__
  1294.     if inspect.isfunction(thing):
  1295.         return 'function ' + thing.__name__
  1296.     if inspect.ismethod(thing):
  1297.         return 'method ' + thing.__name__
  1298.     if type(thing) is types.InstanceType:
  1299.         return 'instance of ' + thing.__class__.__name__
  1300.     return type(thing).__name__
  1301.  
  1302. def locate(path, forceload=0):
  1303.     """Locate an object by name or dotted path, importing as necessary."""
  1304.     parts = split(path, '.')
  1305.     module, n = None, 0
  1306.     while n < len(parts):
  1307.         nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
  1308.         if nextmodule: module, n = nextmodule, n + 1
  1309.         else: break
  1310.     if module:
  1311.         object = module
  1312.         for part in parts[n:]:
  1313.             try: object = getattr(object, part)
  1314.             except AttributeError: return None
  1315.         return object
  1316.     else:
  1317.         import __builtin__
  1318.         if hasattr(__builtin__, path):
  1319.             return getattr(__builtin__, path)
  1320.  
  1321. # --------------------------------------- interactive interpreter interface
  1322.  
  1323. text = TextDoc()
  1324. html = HTMLDoc()
  1325.  
  1326. def resolve(thing, forceload=0):
  1327.     """Given an object or a path to an object, get the object and its name."""
  1328.     if isinstance(thing, str):
  1329.         object = locate(thing, forceload)
  1330.         if not object:
  1331.             raise ImportError, 'no Python documentation found for %r' % thing
  1332.         return object, thing
  1333.     else:
  1334.         return thing, getattr(thing, '__name__', None)
  1335.  
  1336. def doc(thing, title='Python Library Documentation: %s', forceload=0):
  1337.     """Display text documentation, given an object or a path to an object."""
  1338.     try:
  1339.         object, name = resolve(thing, forceload)
  1340.         desc = describe(object)
  1341.         module = inspect.getmodule(object)
  1342.         if name and '.' in name:
  1343.             desc += ' in ' + name[:name.rfind('.')]
  1344.         elif module and module is not object:
  1345.             desc += ' in module ' + module.__name__
  1346.         pager(title % desc + '\n\n' + text.document(object, name))
  1347.     except (ImportError, ErrorDuringImport), value:
  1348.         print value
  1349.  
  1350. def writedoc(thing, forceload=0):
  1351.     """Write HTML documentation to a file in the current directory."""
  1352.     try:
  1353.         object, name = resolve(thing, forceload)
  1354.         page = html.page(describe(object), html.document(object, name))
  1355.         file = open(name + '.html', 'w')
  1356.         file.write(page)
  1357.         file.close()
  1358.         print 'wrote', name + '.html'
  1359.     except (ImportError, ErrorDuringImport), value:
  1360.         print value
  1361.  
  1362. def writedocs(dir, pkgpath='', done=None):
  1363.     """Write out HTML documentation for all modules in a directory tree."""
  1364.     if done is None: done = {}
  1365.     for file in os.listdir(dir):
  1366.         path = os.path.join(dir, file)
  1367.         if ispackage(path):
  1368.             writedocs(path, pkgpath + file + '.', done)
  1369.         elif os.path.isfile(path):
  1370.             modname = inspect.getmodulename(path)
  1371.             if modname:
  1372.                 modname = pkgpath + modname
  1373.                 if not done.has_key(modname):
  1374.                     done[modname] = 1
  1375.                     writedoc(modname)
  1376.  
  1377. class Helper:
  1378.     keywords = {
  1379.         'and': 'BOOLEAN',
  1380.         'assert': ('ref/assert', ''),
  1381.         'break': ('ref/break', 'while for'),
  1382.         'class': ('ref/class', 'CLASSES SPECIALMETHODS'),
  1383.         'continue': ('ref/continue', 'while for'),
  1384.         'def': ('ref/function', ''),
  1385.         'del': ('ref/del', 'BASICMETHODS'),
  1386.         'elif': 'if',
  1387.         'else': ('ref/if', 'while for'),
  1388.         'except': 'try',
  1389.         'exec': ('ref/exec', ''),
  1390.         'finally': 'try',
  1391.         'for': ('ref/for', 'break continue while'),
  1392.         'from': 'import',
  1393.         'global': ('ref/global', 'NAMESPACES'),
  1394.         'if': ('ref/if', 'TRUTHVALUE'),
  1395.         'import': ('ref/import', 'MODULES'),
  1396.         'in': ('ref/comparisons', 'SEQUENCEMETHODS2'),
  1397.         'is': 'COMPARISON',
  1398.         'lambda': ('ref/lambda', 'FUNCTIONS'),
  1399.         'not': 'BOOLEAN',
  1400.         'or': 'BOOLEAN',
  1401.         'pass': 'PASS',
  1402.         'print': ('ref/print', ''),
  1403.         'raise': ('ref/raise', 'EXCEPTIONS'),
  1404.         'return': ('ref/return', 'FUNCTIONS'),
  1405.         'try': ('ref/try', 'EXCEPTIONS'),
  1406.         'while': ('ref/while', 'break continue if TRUTHVALUE'),
  1407.     }
  1408.  
  1409.     topics = {
  1410.         'TYPES': ('ref/types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS FUNCTIONS CLASSES MODULES FILES inspect'),
  1411.         'STRINGS': ('ref/strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING TYPES'),
  1412.         'STRINGMETHODS': ('lib/string-methods', 'STRINGS FORMATTING'),
  1413.         'FORMATTING': ('lib/typesseq-strings', 'OPERATORS'),
  1414.         'UNICODE': ('ref/unicode', 'encodings unicode TYPES STRING'),
  1415.         'NUMBERS': ('ref/numbers', 'INTEGER FLOAT COMPLEX TYPES'),
  1416.         'INTEGER': ('ref/integers', 'int range'),
  1417.         'FLOAT': ('ref/floating', 'float math'),
  1418.         'COMPLEX': ('ref/imaginary', 'complex cmath'),
  1419.         'SEQUENCES': ('lib/typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'),
  1420.         'MAPPINGS': 'DICTIONARIES',
  1421.         'FUNCTIONS': ('lib/typesfunctions', 'def TYPES'),
  1422.         'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'),
  1423.         'CODEOBJECTS': ('lib/bltin-code-objects', 'compile FUNCTIONS TYPES'),
  1424.         'TYPEOBJECTS': ('lib/bltin-type-objects', 'types TYPES'),
  1425.         'FRAMEOBJECTS': 'TYPES',
  1426.         'TRACEBACKS': 'TYPES',
  1427.         'NONE': ('lib/bltin-null-object', ''),
  1428.         'ELLIPSIS': ('lib/bltin-ellipsis-object', 'SLICINGS'),
  1429.         'FILES': ('lib/bltin-file-objects', ''),
  1430.         'SPECIALATTRIBUTES': ('lib/specialattrs', ''),
  1431.         'CLASSES': ('ref/types', 'class SPECIALMETHODS PRIVATENAMES'),
  1432.         'MODULES': ('lib/typesmodules', 'import'),
  1433.         'PACKAGES': 'import',
  1434.         'EXPRESSIONS': ('ref/summary', 'lambda or and not in is BOOLEAN COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES LISTS DICTIONARIES BACKQUOTES'),
  1435.         'OPERATORS': 'EXPRESSIONS',
  1436.         'PRECEDENCE': 'EXPRESSIONS',
  1437.         'OBJECTS': ('ref/objects', 'TYPES'),
  1438.         'SPECIALMETHODS': ('ref/specialnames', 'BASICMETHODS ATTRIBUTEMETHODS CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'),
  1439.         'BASICMETHODS': ('ref/customization', 'cmp hash repr str SPECIALMETHODS'),
  1440.         'ATTRIBUTEMETHODS': ('ref/attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
  1441.         'CALLABLEMETHODS': ('ref/callable-types', 'CALLS SPECIALMETHODS'),
  1442.         'SEQUENCEMETHODS1': ('ref/sequence-types', 'SEQUENCES SEQUENCEMETHODS2 SPECIALMETHODS'),
  1443.         'SEQUENCEMETHODS2': ('ref/sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 SPECIALMETHODS'),
  1444.         'MAPPINGMETHODS': ('ref/sequence-types', 'MAPPINGS SPECIALMETHODS'),
  1445.         'NUMBERMETHODS': ('ref/numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT SPECIALMETHODS'),
  1446.         'EXECUTION': ('ref/execframes', ''),
  1447.         'NAMESPACES': ('ref/execframes', 'global ASSIGNMENT DELETION'),
  1448.         'SCOPING': 'NAMESPACES',
  1449.         'FRAMES': 'NAMESPACES',
  1450.         'EXCEPTIONS': ('ref/exceptions', 'try except finally raise'),
  1451.         'COERCIONS': 'CONVERSIONS',
  1452.         'CONVERSIONS': ('ref/conversions', ''),
  1453.         'IDENTIFIERS': ('ref/identifiers', 'keywords SPECIALIDENTIFIERS'),
  1454.         'SPECIALIDENTIFIERS': ('ref/id-classes', ''),
  1455.         'PRIVATENAMES': ('ref/atom-identifiers', ''),
  1456.         'LITERALS': ('ref/atom-literals', 'STRINGS BACKQUOTES NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'),
  1457.         'TUPLES': 'SEQUENCES',
  1458.         'TUPLELITERALS': ('ref/exprlists', 'TUPLES LITERALS'),
  1459.         'LISTS': ('lib/typesseq-mutable', 'LISTLITERALS'),
  1460.         'LISTLITERALS': ('ref/lists', 'LISTS LITERALS'),
  1461.         'DICTIONARIES': ('lib/typesmapping', 'DICTIONARYLITERALS'),
  1462.         'DICTIONARYLITERALS': ('ref/dict', 'DICTIONARIES LITERALS'),
  1463.         'BACKQUOTES': ('ref/string-conversions', 'repr str STRINGS LITERALS'),
  1464.         'ATTRIBUTES': ('ref/attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'),
  1465.         'SUBSCRIPTS': ('ref/subscriptions', 'SEQUENCEMETHODS1'),
  1466.         'SLICINGS': ('ref/slicings', 'SEQUENCEMETHODS2'),
  1467.         'CALLS': ('ref/calls', 'EXPRESSIONS'),
  1468.         'POWER': ('ref/power', 'EXPRESSIONS'),
  1469.         'UNARY': ('ref/unary', 'EXPRESSIONS'),
  1470.         'BINARY': ('ref/binary', 'EXPRESSIONS'),
  1471.         'SHIFTING': ('ref/shifting', 'EXPRESSIONS'),
  1472.         'BITWISE': ('ref/bitwise', 'EXPRESSIONS'),
  1473.         'COMPARISON': ('ref/comparisons', 'EXPRESSIONS BASICMETHODS'),
  1474.         'BOOLEAN': ('ref/lambda', 'EXPRESSIONS TRUTHVALUE'),
  1475.         'ASSERTION': 'assert',
  1476.         'ASSIGNMENT': ('ref/assignment', 'AUGMENTEDASSIGNMENT'),
  1477.         'AUGMENTEDASSIGNMENT': ('ref/augassign', 'NUMBERMETHODS'),
  1478.         'DELETION': 'del',
  1479.         'PRINTING': 'print',
  1480.         'RETURNING': 'return',
  1481.         'IMPORTING': 'import',
  1482.         'CONDITIONAL': 'if',
  1483.         'LOOPING': ('ref/compound', 'for while break continue'),
  1484.         'TRUTHVALUE': ('lib/truth', 'if while and or not BASICMETHODS'),
  1485.         'DEBUGGING': ('lib/module-pdb', 'pdb'),
  1486.     }
  1487.  
  1488.     def __init__(self, input, output):
  1489.         self.input = input
  1490.         self.output = output
  1491.         self.docdir = None
  1492.         execdir = os.path.dirname(sys.executable)
  1493.         homedir = os.environ.get('PYTHONHOME')
  1494.         for dir in [os.environ.get('PYTHONDOCS'),
  1495.                     homedir and os.path.join(homedir, 'doc'),
  1496.                     os.path.join(execdir, 'doc'),
  1497.                     '/usr/doc/python-docs-' + split(sys.version)[0],
  1498.                     '/usr/doc/python-' + split(sys.version)[0],
  1499.                     '/usr/doc/python-docs-' + sys.version[:3],
  1500.                     '/usr/doc/python-' + sys.version[:3]]:
  1501.             if dir and os.path.isdir(os.path.join(dir, 'lib')):
  1502.                 self.docdir = dir
  1503.  
  1504.     def __repr__(self):
  1505.         if inspect.stack()[1][3] == '?':
  1506.             self()
  1507.             return ''
  1508.         return '<pydoc.Helper instance>'
  1509.  
  1510.     def __call__(self, request=None):
  1511.         if request is not None:
  1512.             self.help(request)
  1513.         else:
  1514.             self.intro()
  1515.             self.interact()
  1516.             self.output.write('''
  1517. You are now leaving help and returning to the Python interpreter.
  1518. If you want to ask for help on a particular object directly from the
  1519. interpreter, you can type "help(object)".  Executing "help('string')"
  1520. has the same effect as typing a particular string at the help> prompt.
  1521. ''')
  1522.  
  1523.     def interact(self):
  1524.         self.output.write('\n')
  1525.         while 1:
  1526.             self.output.write('help> ')
  1527.             self.output.flush()
  1528.             try:
  1529.                 request = self.input.readline()
  1530.                 if not request: break
  1531.             except KeyboardInterrupt: break
  1532.             request = strip(replace(request, '"', '', "'", ''))
  1533.             if lower(request) in ['q', 'quit']: break
  1534.             self.help(request)
  1535.  
  1536.     def help(self, request):
  1537.         if type(request) is type(''):
  1538.             if request == 'help': self.intro()
  1539.             elif request == 'keywords': self.listkeywords()
  1540.             elif request == 'topics': self.listtopics()
  1541.             elif request == 'modules': self.listmodules()
  1542.             elif request[:8] == 'modules ':
  1543.                 self.listmodules(split(request)[1])
  1544.             elif self.keywords.has_key(request): self.showtopic(request)
  1545.             elif self.topics.has_key(request): self.showtopic(request)
  1546.             elif request: doc(request, 'Help on %s:')
  1547.         elif isinstance(request, Helper): self()
  1548.         else: doc(request, 'Help on %s:')
  1549.         self.output.write('\n')
  1550.  
  1551.     def intro(self):
  1552.         self.output.write('''
  1553. Welcome to Python %s!  This is the online help utility.
  1554.  
  1555. If this is your first time using Python, you should definitely check out
  1556. the tutorial on the Internet at http://www.python.org/doc/tut/.
  1557.  
  1558. Enter the name of any module, keyword, or topic to get help on writing
  1559. Python programs and using Python modules.  To quit this help utility and
  1560. return to the interpreter, just type "quit".
  1561.  
  1562. To get a list of available modules, keywords, or topics, type "modules",
  1563. "keywords", or "topics".  Each module also comes with a one-line summary
  1564. of what it does; to list the modules whose summaries contain a given word
  1565. such as "spam", type "modules spam".
  1566. ''' % sys.version[:3])
  1567.  
  1568.     def list(self, items, columns=4, width=80):
  1569.         items = items[:]
  1570.         items.sort()
  1571.         colw = width / columns
  1572.         rows = (len(items) + columns - 1) / columns
  1573.         for row in range(rows):
  1574.             for col in range(columns):
  1575.                 i = col * rows + row
  1576.                 if i < len(items):
  1577.                     self.output.write(items[i])
  1578.                     if col < columns - 1:
  1579.                         self.output.write(' ' + ' ' * (colw-1 - len(items[i])))
  1580.             self.output.write('\n')
  1581.  
  1582.     def listkeywords(self):
  1583.         self.output.write('''
  1584. Here is a list of the Python keywords.  Enter any keyword to get more help.
  1585.  
  1586. ''')
  1587.         self.list(self.keywords.keys())
  1588.  
  1589.     def listtopics(self):
  1590.         self.output.write('''
  1591. Here is a list of available topics.  Enter any topic name to get more help.
  1592.  
  1593. ''')
  1594.         self.list(self.topics.keys())
  1595.  
  1596.     def showtopic(self, topic):
  1597.         if not self.docdir:
  1598.             self.output.write('''
  1599. Sorry, topic and keyword documentation is not available because the Python
  1600. HTML documentation files could not be found.  If you have installed them,
  1601. please set the environment variable PYTHONDOCS to indicate their location.
  1602. ''')
  1603.             return
  1604.         target = self.topics.get(topic, self.keywords.get(topic))
  1605.         if not target:
  1606.             self.output.write('no documentation found for %s\n' % repr(topic))
  1607.             return
  1608.         if type(target) is type(''):
  1609.             return self.showtopic(target)
  1610.  
  1611.         filename, xrefs = target
  1612.         filename = self.docdir + '/' + filename + '.html'
  1613.         try:
  1614.             file = open(filename)
  1615.         except:
  1616.             self.output.write('could not read docs from %s\n' % filename)
  1617.             return
  1618.  
  1619.         divpat = re.compile('<div[^>]*navigat.*?</div.*?>', re.I | re.S)
  1620.         addrpat = re.compile('<address.*?>.*?</address.*?>', re.I | re.S)
  1621.         document = re.sub(addrpat, '', re.sub(divpat, '', file.read()))
  1622.         file.close()
  1623.  
  1624.         import htmllib, formatter, StringIO
  1625.         buffer = StringIO.StringIO()
  1626.         parser = htmllib.HTMLParser(
  1627.             formatter.AbstractFormatter(formatter.DumbWriter(buffer)))
  1628.         parser.start_table = parser.do_p
  1629.         parser.end_table = lambda parser=parser: parser.do_p({})
  1630.         parser.start_tr = parser.do_br
  1631.         parser.start_td = parser.start_th = lambda a, b=buffer: b.write('\t')
  1632.         parser.feed(document)
  1633.         buffer = replace(buffer.getvalue(), '\xa0', ' ', '\n', '\n  ')
  1634.         pager('  ' + strip(buffer) + '\n')
  1635.         if xrefs:
  1636.             buffer = StringIO.StringIO()
  1637.             formatter.DumbWriter(buffer).send_flowing_data(
  1638.                 'Related help topics: ' + join(split(xrefs), ', ') + '\n')
  1639.             self.output.write('\n%s\n' % buffer.getvalue())
  1640.  
  1641.     def listmodules(self, key=''):
  1642.         if key:
  1643.             self.output.write('''
  1644. Here is a list of matching modules.  Enter any module name to get more help.
  1645.  
  1646. ''')
  1647.             apropos(key)
  1648.         else:
  1649.             self.output.write('''
  1650. Please wait a moment while I gather a list of all available modules...
  1651.  
  1652. ''')
  1653.             modules = {}
  1654.             def callback(path, modname, desc, modules=modules):
  1655.                 if modname and modname[-9:] == '.__init__':
  1656.                     modname = modname[:-9] + ' (package)'
  1657.                 if find(modname, '.') < 0:
  1658.                     modules[modname] = 1
  1659.             ModuleScanner().run(callback)
  1660.             self.list(modules.keys())
  1661.             self.output.write('''
  1662. Enter any module name to get more help.  Or, type "modules spam" to search
  1663. for modules whose descriptions contain the word "spam".
  1664. ''')
  1665.  
  1666. help = Helper(sys.stdin, sys.stdout)
  1667.  
  1668. class Scanner:
  1669.     """A generic tree iterator."""
  1670.     def __init__(self, roots, children, descendp):
  1671.         self.roots = roots[:]
  1672.         self.state = []
  1673.         self.children = children
  1674.         self.descendp = descendp
  1675.  
  1676.     def next(self):
  1677.         if not self.state:
  1678.             if not self.roots:
  1679.                 return None
  1680.             root = self.roots.pop(0)
  1681.             self.state = [(root, self.children(root))]
  1682.         node, children = self.state[-1]
  1683.         if not children:
  1684.             self.state.pop()
  1685.             return self.next()
  1686.         child = children.pop(0)
  1687.         if self.descendp(child):
  1688.             self.state.append((child, self.children(child)))
  1689.         return child
  1690.  
  1691. class ModuleScanner(Scanner):
  1692.     """An interruptible scanner that searches module synopses."""
  1693.     def __init__(self):
  1694.         roots = map(lambda dir: (dir, ''), pathdirs())
  1695.         Scanner.__init__(self, roots, self.submodules, self.isnewpackage)
  1696.         self.inodes = map(lambda (dir, pkg): os.stat(dir)[1], roots)
  1697.  
  1698.     def submodules(self, (dir, package)):
  1699.         children = []
  1700.         for file in os.listdir(dir):
  1701.             path = os.path.join(dir, file)
  1702.             if ispackage(path):
  1703.                 children.append((path, package + (package and '.') + file))
  1704.             else:
  1705.                 children.append((path, package))
  1706.         children.sort() # so that spam.py comes before spam.pyc or spam.pyo
  1707.         return children
  1708.  
  1709.     def isnewpackage(self, (dir, package)):
  1710.         inode = os.path.exists(dir) and os.stat(dir)[1]
  1711.         if not (os.path.islink(dir) and inode in self.inodes):
  1712.             self.inodes.append(inode) # detect circular symbolic links
  1713.             return ispackage(dir)
  1714.  
  1715.     def run(self, callback, key=None, completer=None):
  1716.         if key: key = lower(key)
  1717.         self.quit = 0
  1718.         seen = {}
  1719.  
  1720.         for modname in sys.builtin_module_names:
  1721.             if modname != '__main__':
  1722.                 seen[modname] = 1
  1723.                 if key is None:
  1724.                     callback(None, modname, '')
  1725.                 else:
  1726.                     desc = split(__import__(modname).__doc__ or '', '\n')[0]
  1727.                     if find(lower(modname + ' - ' + desc), key) >= 0:
  1728.                         callback(None, modname, desc)
  1729.  
  1730.         while not self.quit:
  1731.             node = self.next()
  1732.             if not node: break
  1733.             path, package = node
  1734.             modname = inspect.getmodulename(path)
  1735.             if os.path.isfile(path) and modname:
  1736.                 modname = package + (package and '.') + modname
  1737.                 if not seen.has_key(modname):
  1738.                     seen[modname] = 1 # if we see spam.py, skip spam.pyc
  1739.                     if key is None:
  1740.                         callback(path, modname, '')
  1741.                     else:
  1742.                         desc = synopsis(path) or ''
  1743.                         if find(lower(modname + ' - ' + desc), key) >= 0:
  1744.                             callback(path, modname, desc)
  1745.         if completer: completer()
  1746.  
  1747. def apropos(key):
  1748.     """Print all the one-line module summaries that contain a substring."""
  1749.     def callback(path, modname, desc):
  1750.         if modname[-9:] == '.__init__':
  1751.             modname = modname[:-9] + ' (package)'
  1752.         print modname, desc and '- ' + desc
  1753.     try: import warnings
  1754.     except ImportError: pass
  1755.     else: warnings.filterwarnings('ignore') # ignore problems during import
  1756.     ModuleScanner().run(callback, key)
  1757.  
  1758. # --------------------------------------------------- web browser interface
  1759.  
  1760. def serve(port, callback=None, completer=None):
  1761.     import BaseHTTPServer, mimetools, select
  1762.  
  1763.     # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded.
  1764.     class Message(mimetools.Message):
  1765.         def __init__(self, fp, seekable=1):
  1766.             Message = self.__class__
  1767.             Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)
  1768.             self.encodingheader = self.getheader('content-transfer-encoding')
  1769.             self.typeheader = self.getheader('content-type')
  1770.             self.parsetype()
  1771.             self.parseplist()
  1772.  
  1773.     class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  1774.         def send_document(self, title, contents):
  1775.             try:
  1776.                 self.send_response(200)
  1777.                 self.send_header('Content-Type', 'text/html')
  1778.                 self.end_headers()
  1779.                 self.wfile.write(html.page(title, contents))
  1780.             except IOError: pass
  1781.  
  1782.         def do_GET(self):
  1783.             path = self.path
  1784.             if path[-5:] == '.html': path = path[:-5]
  1785.             if path[:1] == '/': path = path[1:]
  1786.             if path and path != '.':
  1787.                 try:
  1788.                     obj = locate(path, forceload=1)
  1789.                 except ErrorDuringImport, value:
  1790.                     self.send_document(path, html.escape(str(value)))
  1791.                     return
  1792.                 if obj:
  1793.                     self.send_document(describe(obj), html.document(obj, path))
  1794.                 else:
  1795.                     self.send_document(path,
  1796. 'no Python documentation found for %s' % repr(path))
  1797.             else:
  1798.                 heading = html.heading(
  1799. '<big><big><strong>Python: Index of Modules</strong></big></big>',
  1800. '#ffffff', '#7799ee')
  1801.                 def bltinlink(name):
  1802.                     return '<a href="%s.html">%s</a>' % (name, name)
  1803.                 names = filter(lambda x: x != '__main__',
  1804.                                sys.builtin_module_names)
  1805.                 contents = html.multicolumn(names, bltinlink)
  1806.                 indices = ['<p>' + html.bigsection(
  1807.                     'Built-in Modules', '#ffffff', '#ee77aa', contents)]
  1808.  
  1809.                 seen = {}
  1810.                 for dir in pathdirs():
  1811.                     indices.append(html.index(dir, seen))
  1812.                 contents = heading + join(indices) + '''<p align=right>
  1813. <font color="#909090" face="helvetica, arial"><strong>
  1814. pydoc</strong> by Ka-Ping Yee <ping@lfw.org></font>'''
  1815.                 self.send_document('Index of Modules', contents)
  1816.  
  1817.         def log_message(self, *args): pass
  1818.  
  1819.     class DocServer(BaseHTTPServer.HTTPServer):
  1820.         def __init__(self, port, callback):
  1821.             host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost'
  1822.             self.address = ('', port)
  1823.             self.url = 'http://%s:%d/' % (host, port)
  1824.             self.callback = callback
  1825.             self.base.__init__(self, self.address, self.handler)
  1826.  
  1827.         def serve_until_quit(self):
  1828.             import select
  1829.             self.quit = 0
  1830.             while not self.quit:
  1831.                 rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
  1832.                 if rd: self.handle_request()
  1833.  
  1834.         def server_activate(self):
  1835.             self.base.server_activate(self)
  1836.             if self.callback: self.callback(self)
  1837.  
  1838.     DocServer.base = BaseHTTPServer.HTTPServer
  1839.     DocServer.handler = DocHandler
  1840.     DocHandler.MessageClass = Message
  1841.     try:
  1842.         try:
  1843.             DocServer(port, callback).serve_until_quit()
  1844.         except (KeyboardInterrupt, select.error):
  1845.             pass
  1846.     finally:
  1847.         if completer: completer()
  1848.  
  1849. # ----------------------------------------------------- graphical interface
  1850.  
  1851. def gui():
  1852.     """Graphical interface (starts web server and pops up a control window)."""
  1853.     class GUI:
  1854.         def __init__(self, window, port=7464):
  1855.             self.window = window
  1856.             self.server = None
  1857.             self.scanner = None
  1858.  
  1859.             import Tkinter
  1860.             self.server_frm = Tkinter.Frame(window)
  1861.             self.title_lbl = Tkinter.Label(self.server_frm,
  1862.                 text='Starting server...\n ')
  1863.             self.open_btn = Tkinter.Button(self.server_frm,
  1864.                 text='open browser', command=self.open, state='disabled')
  1865.             self.quit_btn = Tkinter.Button(self.server_frm,
  1866.                 text='quit serving', command=self.quit, state='disabled')
  1867.  
  1868.             self.search_frm = Tkinter.Frame(window)
  1869.             self.search_lbl = Tkinter.Label(self.search_frm, text='Search for')
  1870.             self.search_ent = Tkinter.Entry(self.search_frm)
  1871.             self.search_ent.bind('<Return>', self.search)
  1872.             self.stop_btn = Tkinter.Button(self.search_frm,
  1873.                 text='stop', pady=0, command=self.stop, state='disabled')
  1874.             if sys.platform == 'win32':
  1875.                 # Trying to hide and show this button crashes under Windows.
  1876.                 self.stop_btn.pack(side='right')
  1877.  
  1878.             self.window.title('pydoc')
  1879.             self.window.protocol('WM_DELETE_WINDOW', self.quit)
  1880.             self.title_lbl.pack(side='top', fill='x')
  1881.             self.open_btn.pack(side='left', fill='x', expand=1)
  1882.             self.quit_btn.pack(side='right', fill='x', expand=1)
  1883.             self.server_frm.pack(side='top', fill='x')
  1884.  
  1885.             self.search_lbl.pack(side='left')
  1886.             self.search_ent.pack(side='right', fill='x', expand=1)
  1887.             self.search_frm.pack(side='top', fill='x')
  1888.             self.search_ent.focus_set()
  1889.  
  1890.             font = ('helvetica', sys.platform == 'win32' and 8 or 10)
  1891.             self.result_lst = Tkinter.Listbox(window, font=font, height=6)
  1892.             self.result_lst.bind('<Button-1>', self.select)
  1893.             self.result_lst.bind('<Double-Button-1>', self.goto)
  1894.             self.result_scr = Tkinter.Scrollbar(window,
  1895.                 orient='vertical', command=self.result_lst.yview)
  1896.             self.result_lst.config(yscrollcommand=self.result_scr.set)
  1897.  
  1898.             self.result_frm = Tkinter.Frame(window)
  1899.             self.goto_btn = Tkinter.Button(self.result_frm,
  1900.                 text='go to selected', command=self.goto)
  1901.             self.hide_btn = Tkinter.Button(self.result_frm,
  1902.                 text='hide results', command=self.hide)
  1903.             self.goto_btn.pack(side='left', fill='x', expand=1)
  1904.             self.hide_btn.pack(side='right', fill='x', expand=1)
  1905.  
  1906.             self.window.update()
  1907.             self.minwidth = self.window.winfo_width()
  1908.             self.minheight = self.window.winfo_height()
  1909.             self.bigminheight = (self.server_frm.winfo_reqheight() +
  1910.                                  self.search_frm.winfo_reqheight() +
  1911.                                  self.result_lst.winfo_reqheight() +
  1912.                                  self.result_frm.winfo_reqheight())
  1913.             self.bigwidth, self.bigheight = self.minwidth, self.bigminheight
  1914.             self.expanded = 0
  1915.             self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
  1916.             self.window.wm_minsize(self.minwidth, self.minheight)
  1917.  
  1918.             import threading
  1919.             threading.Thread(
  1920.                 target=serve, args=(port, self.ready, self.quit)).start()
  1921.  
  1922.         def ready(self, server):
  1923.             self.server = server
  1924.             self.title_lbl.config(
  1925.                 text='Python documentation server at\n' + server.url)
  1926.             self.open_btn.config(state='normal')
  1927.             self.quit_btn.config(state='normal')
  1928.  
  1929.         def open(self, event=None, url=None):
  1930.             url = url or self.server.url
  1931.             try:
  1932.                 import webbrowser
  1933.                 webbrowser.open(url)
  1934.             except ImportError: # pre-webbrowser.py compatibility
  1935.                 if sys.platform == 'win32':
  1936.                     os.system('start "%s"' % url)
  1937.                 elif sys.platform == 'mac':
  1938.                     try: import ic
  1939.                     except ImportError: pass
  1940.                     else: ic.launchurl(url)
  1941.                 else:
  1942.                     rc = os.system('netscape -remote "openURL(%s)" &' % url)
  1943.                     if rc: os.system('netscape "%s" &' % url)
  1944.  
  1945.         def quit(self, event=None):
  1946.             if self.server:
  1947.                 self.server.quit = 1
  1948.             self.window.quit()
  1949.  
  1950.         def search(self, event=None):
  1951.             key = self.search_ent.get()
  1952.             self.stop_btn.pack(side='right')
  1953.             self.stop_btn.config(state='normal')
  1954.             self.search_lbl.config(text='Searching for "%s"...' % key)
  1955.             self.search_ent.forget()
  1956.             self.search_lbl.pack(side='left')
  1957.             self.result_lst.delete(0, 'end')
  1958.             self.goto_btn.config(state='disabled')
  1959.             self.expand()
  1960.  
  1961.             import threading
  1962.             if self.scanner:
  1963.                 self.scanner.quit = 1
  1964.             self.scanner = ModuleScanner()
  1965.             threading.Thread(target=self.scanner.run,
  1966.                              args=(self.update, key, self.done)).start()
  1967.  
  1968.         def update(self, path, modname, desc):
  1969.             if modname[-9:] == '.__init__':
  1970.                 modname = modname[:-9] + ' (package)'
  1971.             self.result_lst.insert('end',
  1972.                 modname + ' - ' + (desc or '(no description)'))
  1973.  
  1974.         def stop(self, event=None):
  1975.             if self.scanner:
  1976.                 self.scanner.quit = 1
  1977.                 self.scanner = None
  1978.  
  1979.         def done(self):
  1980.             self.scanner = None
  1981.             self.search_lbl.config(text='Search for')
  1982.             self.search_lbl.pack(side='left')
  1983.             self.search_ent.pack(side='right', fill='x', expand=1)
  1984.             if sys.platform != 'win32': self.stop_btn.forget()
  1985.             self.stop_btn.config(state='disabled')
  1986.  
  1987.         def select(self, event=None):
  1988.             self.goto_btn.config(state='normal')
  1989.  
  1990.         def goto(self, event=None):
  1991.             selection = self.result_lst.curselection()
  1992.             if selection:
  1993.                 modname = split(self.result_lst.get(selection[0]))[0]
  1994.                 self.open(url=self.server.url + modname + '.html')
  1995.  
  1996.         def collapse(self):
  1997.             if not self.expanded: return
  1998.             self.result_frm.forget()
  1999.             self.result_scr.forget()
  2000.             self.result_lst.forget()
  2001.             self.bigwidth = self.window.winfo_width()
  2002.             self.bigheight = self.window.winfo_height()
  2003.             self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
  2004.             self.window.wm_minsize(self.minwidth, self.minheight)
  2005.             self.expanded = 0
  2006.  
  2007.         def expand(self):
  2008.             if self.expanded: return
  2009.             self.result_frm.pack(side='bottom', fill='x')
  2010.             self.result_scr.pack(side='right', fill='y')
  2011.             self.result_lst.pack(side='top', fill='both', expand=1)
  2012.             self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))
  2013.             self.window.wm_minsize(self.minwidth, self.bigminheight)
  2014.             self.expanded = 1
  2015.  
  2016.         def hide(self, event=None):
  2017.             self.stop()
  2018.             self.collapse()
  2019.  
  2020.     import Tkinter
  2021.     try:
  2022.         gui = GUI(Tkinter.Tk())
  2023.         Tkinter.mainloop()
  2024.     except KeyboardInterrupt:
  2025.         pass
  2026.  
  2027. # -------------------------------------------------- command-line interface
  2028.  
  2029. def ispath(x):
  2030.     return isinstance(x, str) and find(x, os.sep) >= 0
  2031.  
  2032. def cli():
  2033.     """Command-line interface (looks at sys.argv to decide what to do)."""
  2034.     import getopt
  2035.     class BadUsage: pass
  2036.  
  2037.     # Scripts don't get the current directory in their path by default.
  2038.     scriptdir = os.path.dirname(sys.argv[0])
  2039.     if scriptdir in sys.path:
  2040.         sys.path.remove(scriptdir)
  2041.     sys.path.insert(0, '.')
  2042.  
  2043.     try:
  2044.         opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w')
  2045.         writing = 0
  2046.  
  2047.         for opt, val in opts:
  2048.             if opt == '-g':
  2049.                 gui()
  2050.                 return
  2051.             if opt == '-k':
  2052.                 apropos(val)
  2053.                 return
  2054.             if opt == '-p':
  2055.                 try:
  2056.                     port = int(val)
  2057.                 except ValueError:
  2058.                     raise BadUsage
  2059.                 def ready(server):
  2060.                     print 'pydoc server ready at %s' % server.url
  2061.                 def stopped():
  2062.                     print 'pydoc server stopped'
  2063.                 serve(port, ready, stopped)
  2064.                 return
  2065.             if opt == '-w':
  2066.                 writing = 1
  2067.  
  2068.         if not args: raise BadUsage
  2069.         for arg in args:
  2070.             if ispath(arg) and not os.path.exists(arg):
  2071.                 print 'file %r does not exist' % arg
  2072.                 break
  2073.             try:
  2074.                 if ispath(arg) and os.path.isfile(arg):
  2075.                     arg = importfile(arg)
  2076.                 if writing:
  2077.                     if ispath(arg) and os.path.isdir(arg):
  2078.                         writedocs(arg)
  2079.                     else:
  2080.                         writedoc(arg)
  2081.                 else:
  2082.                     doc(arg)
  2083.             except ErrorDuringImport, value:
  2084.                 print value
  2085.  
  2086.     except (getopt.error, BadUsage):
  2087.         cmd = sys.argv[0]
  2088.         print """pydoc - the Python documentation tool
  2089.  
  2090. %s <name> ...
  2091.     Show text documentation on something.  <name> may be the name of a
  2092.     function, module, or package, or a dotted reference to a class or
  2093.     function within a module or module in a package.  If <name> contains
  2094.     a '%s', it is used as the path to a Python source file to document.
  2095.  
  2096. %s -k <keyword>
  2097.     Search for a keyword in the synopsis lines of all available modules.
  2098.  
  2099. %s -p <port>
  2100.     Start an HTTP server on the given port on the local machine.
  2101.  
  2102. %s -g
  2103.     Pop up a graphical interface for finding and serving documentation.
  2104.  
  2105. %s -w <name> ...
  2106.     Write out the HTML documentation for a module to a file in the current
  2107.     directory.  If <name> contains a '%s', it is treated as a filename; if
  2108.     it names a directory, documentation is written for all the contents.
  2109. """ % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
  2110.  
  2111. if __name__ == '__main__': cli()
  2112.